<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('公告编码')" prop="noticeCode">
            <el-input v-model="form.noticeCode" :placeholder="$t('公告编码')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('公告类型')" prop="noticeType">
            <el-input v-model="form.noticeType" :placeholder="$t('公告类型')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('备注')" prop="remark">
            <el-input v-model="form.remark" type="textarea" :placeholder="$t('备注')" show-word-limit maxlength="2000" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('默认发送用户')" prop="defaultSendUser">
            <UserSelect v-model="form.defaultSendUser" multiple :placeholder="$t('请选择')" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('默认发送相对角色')" prop="defaultSendRole">
            <dictSelect
              v-model="form.defaultSendRole"
              dictionary="msg_role"
              multiple
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('是否提醒自己')" prop="remindYourself">
            <el-radio-group v-model="form.remindYourself">
              <el-radio
                v-for="item in sysYesNoOption"
                :key="item.dictValue"
                :label="$t(item.dictValue)"
              > {{ $t(item.dictLabel) }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('是否提醒团队成员')" prop="reminderTeam">
            <el-radio-group v-model="form.reminderTeam">
              <el-radio
                v-for="item in sysYesNoOption"
                :key="item.dictValue"
                :label="$t(item.dictValue)"
              > {{ $t(item.dictLabel) }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('是否自定义配置通知用户')" prop="isCustomSend">
            <el-radio-group v-model="form.isCustomSend" @change="onchange('send')">
              <el-radio
                v-for="item in sysYesNoOption"
                :key="item.dictValue"
                :label="$t(item.dictValue)"
              > {{ $t(item.dictLabel) }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('是否配置抄送用户')" prop="isCustomCc">
            <span slot="label">
              {{ $t('是否配置抄送用户') }}
              <el-tooltip :content="$t('抄送用户仅限于邮件通知')" placement="right">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <el-radio-group v-model="form.isCustomCc" @change="onchange('cc')">
              <el-radio
                v-for="item in sysYesNoOption"
                :key="item.dictValue"
                :label="$t(item.dictValue)"
              > {{ $t(item.dictLabel) }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col v-show="form.isCustomSend === 'Y'" :span="24">
          <el-form-item :label="$t('通知用户SQL')" prop="sendUserSql">
            <span slot="label">
              {{ $t('通知用户脚本') }}
              <el-tooltip :content="$t('仅限于查询语句，且只能存在一个字段，该字段为用户id即可')" placement="right">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <textarea ref="sendUserSql" v-model="form.sendUserSql" class="codesql" style="height:200px;width:600px;" />
          </el-form-item>
        </el-col>
        <el-col v-show="form.isCustomCc === 'Y'" :span="24">
          <el-form-item :label="$t('抄送用户脚本')" prop="ccUserSql">
            <span slot="label">
              {{ $t('抄送用户脚本') }}
              <el-tooltip :content="$t('仅限于查询语句，且只能存在一个字段，该字段为用户id即可')" placement="right">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <textarea ref="ccUserSql" v-model="form.ccUserSql" class="codesql" style="height:200px;width:600px;" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('通知方式')" prop="noticeMode">
            <el-checkbox-group v-model="form.noticeMode" @change="noticeModeChange">
              <el-checkbox
                v-for="(dict, index) in noticeModeOptions"
                :key="index"
                :label="dict.dictValue"
                border
              >{{ $t(dict.dictLabel) }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
        <el-col v-if="form.noticeMode.includes('XTTX')" :span="12">
          <el-form-item :label="$t('系统通知标题')" prop="systemNoticeTitle">
            <el-input v-model="form.systemNoticeTitle" :placeholder="$t('系统通知标题')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col v-if="form.noticeMode.includes('XTTX')" :span="24">
          <el-form-item :label="$t('系统通知内容')" prop="systemNoticeContent">
            <EditorTxt v-model="form.systemNoticeContent" :height="400" />
            <!--<el-input v-model="form.systemNoticeContent" type="textarea" :placeholder="请输入内容" :autosize="{minRows: 3, maxRows: 20}" show-word-limit maxlength="1000" />-->
          </el-form-item>
        </el-col>
        <el-col v-if="form.noticeMode.includes('EMAIL')" :span="12">
          <el-form-item :label="$t('邮件通知标题')" prop="mailNoticeTitle">
            <el-input v-model="form.mailNoticeTitle" :placeholder="$t('邮件通知标题')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col v-if="form.noticeMode.includes('EMAIL')" :span="24">
          <el-form-item :label="$t('邮件通知内容')" prop="mailNoticeContent">
            <EditorTxt v-model="form.mailNoticeContent" :height="400" />
            <!--<el-input v-model="form.mailNoticeContent" type="textarea" :placeholder="请输入内容" :autosize="{minRows: 3, maxRows: 20}" show-word-limit maxlength="1000" />-->
          </el-form-item>
        </el-col>
        <el-col v-if="form.noticeMode.includes('APP')" :span="12">
          <el-form-item :label="$t('App通知标题')" prop="appNoticeTitle">
            <el-input v-model="form.appNoticeTitle" :placeholder="$t('App通知标题')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col v-if="form.noticeMode.includes('APP')" :span="24">
          <el-form-item :label="$t('App通知内容')" prop="appNoticeContent">
            <el-input v-model="form.appNoticeContent" type="textarea" :placeholder="$t('App通知内容')" :autosize="{minRows: 3, maxRows: 20}" show-word-limit maxlength="1000" />
          </el-form-item>
        </el-col>
        <el-col v-if="form.noticeMode.includes('QYWX')" :span="12">
          <el-form-item :label="$t('企业微信通知标题')" prop="wechatNoticeTitle">
            <el-input v-model="form.wechatNoticeTitle" :placeholder="$t('企业微信通知标题')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col v-if="form.noticeMode.includes('QYWX')" :span="24">
          <el-form-item :label="$t('企业微信通知内容')" prop="wechatNoticeContent">
            <el-input v-model="form.wechatNoticeContent" type="textarea" :placeholder="$t('企业微信通知内容')" :autosize="{minRows: 3, maxRows: 20}" show-word-limit maxlength="1000" />
          </el-form-item>
        </el-col>
        <el-col v-if="form.noticeMode.includes('SMS')" :span="12">
          <el-form-item :label="$t('短信通知编码')" prop="smsNoticeCode">
            <el-input v-model="form.smsNoticeCode" :placeholder="$t('短信通知编码')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col v-if="form.noticeMode.includes('DD')" :span="12">
          <el-form-item :label="$t('钉钉通知标题')" prop="dingTalkNoticeContent">
            <el-input v-model="form.dingTalkNoticeTitle" :placeholder="$t('钉钉通知标题')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col v-if="form.noticeMode.includes('DD')" :span="24">
          <el-form-item :label="$t('钉钉通知内容')" prop="dingTalkNoticeContent">
            <mavon-editor v-model="form.dingTalkNoticeContent" class="mavon-editor" :placeholder="$t('钉钉通知内容')" :toolbars-flag="false" :html="false" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col v-if="form.noticeMode.includes('FS')" :span="12">
          <el-form-item :label="$t('飞书通知标题')" prop="fsNoticeTitle">
            <el-input v-model="form.fsNoticeTitle" :placeholder="$t('飞书通知标题')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col v-if="form.noticeMode.includes('FS')" :span="24">
          <el-form-item :label="$t('飞书通知内容')" prop="fsNoticeContent">
            <mavon-editor v-model="form.fsNoticeContent" class="mavon-editor" :placeholder="$t('飞书通知内容')" :toolbars-flag="false" :html="false" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <!--        <el-col v-if="form.noticeMode.includes('GZH')" :span="12">-->
        <!--          <el-form-item :label="$t('公众号通知标题')" prop="mpNoticeTitle">-->
        <!--            <el-input v-model="form.mpNoticeTitle" :placeholder="$t('公众号通知标题')" show-word-limit maxlength="100" />-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
        <el-col v-if="form.noticeMode.includes('GZH')" :span="12">
          <el-form-item :label="$t('公众号通知模板ID')" prop="mpTemplateId">
            <el-input v-model="form.mpTemplateId" :placeholder="$t('公众号通知模板ID')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col v-if="form.noticeMode.includes('GZH')" :span="24" style="margin-top: 10px;">
          <el-table v-loading="loading" class="mappingData" :data="form.mpMsgTemplateFieldMappingList" border tooltip-effect="darkTable">
            <el-table-column :label="$t('内置模板字段')" align="center" prop="sourceField">
              <template slot="header" slot-scope="{}">
                <span style="color: red">*</span>
                <span>{{ $t('内置模板字段') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'mpMsgTemplateFieldMappingList.' + scope.$index + '.sourceField'" :rules="listRules.sourceField">
                  <el-select v-model="scope.row.sourceField">
                    <el-option v-for="field in form.templateFieldList" :key="field.id" :value="field.fieldName" :label="field.fieldName" />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('第三方模板字段')" align="center" prop="toField">
              <template slot="header" slot-scope="{}">
                <span style="color: red">*</span>
                <span>{{ $t('第三方模板字段') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'mpMsgTemplateFieldMappingList.' + scope.$index + '.toField'" :rules="listRules.toField">
                  <el-input v-model="scope.row.toField" :placeholder="$t('第三方模板字段')" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('备注')" align="center" prop="remark">
              <template slot-scope="scope">
                <el-form-item>
                  <el-input v-model="scope.row.remark" :placeholder="$t('备注')" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('操作')" align="center" class-name="small-padding fixed-width" width="200">
              <template slot-scope="scope">
                <el-button
                  v-hasPermi="['message:mapping:remove']"
                  size="small"
                  type="text"
                  icon="el-icon-delete"
                  @click="deleteHandle(scope.row)"
                >{{ $t('删除') }}</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="tol">
            <el-button style="margin-top: 10px;" size="mini" icon="el-icon-plus" type="primary" @click="addMappingField">添加</el-button>
          </div>
        </el-col>
      </el-row>
      <div class="area-header">
        <span class="area-header-title">{{ $t('关键字列表') }}</span>
      </div>
      <el-table class="nowrapTable formTable" :data="form.templateFieldList" border>
        <el-table-column :label="$t('字段名称')" align="center">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('字段名称') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'templateFieldList.' + scope.$index + '.fieldName'" :rules="listRules">
              <el-input v-model="scope.row.fieldName" :placeholder="$t('字段名称')" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('备注')" align="center">
          <template slot-scope="scope">
            <el-form-item>
              <el-input v-model="scope.row.remark" :placeholder="$t('备注')" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('操作')" align="center" width="80">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-delete" @click="delTemplate(scope.$index, scope.row)">{{ $t('删除') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="tol">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="addTemplate">{{ $t("添加") }}</el-button>
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <SaveBtn has-permi="system:msgtemplate" />
    </div>
  </div>
</template>

<script>
    import { saveMsgTemplate, getMsgTemplate } from '@/api/system/message/msgTemplate'
    import EditorTxt from '@/components/Editor'
    import 'codemirror/theme/ambiance.css'
    import 'codemirror/lib/codemirror.css'
    import 'codemirror/addon/hint/show-hint.css'

    const CodeMirror = require('codemirror/lib/codemirror')
    require('codemirror/addon/edit/matchbrackets')
    require('codemirror/addon/selection/active-line')
    require('codemirror/mode/sql/sql')
    require('codemirror/addon/hint/show-hint')
    require('codemirror/addon/hint/sql-hint')
    export default {
        components: {
          EditorTxt
        },
        data() {
            return {
                // 通知方式字典
                noticeModeOptions: [], // 表单参数
                form: {
                  noticeMode: []
                },
                sysYesNoOption: [],
                // 遮罩层
                loading: false,
                // 表单校验
                rules: {
                   noticeCode: [
                     { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                   ], noticeType: [
                     { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                   ], noticeMode: [
                     { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
                   ], systemNoticeTitle: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], mailNoticeTitle: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], appNoticeTitle: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], wechatNoticeTitle: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], wechatNoticeContent: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], smsNoticeCode: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], systemNoticeContent: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], mailNoticeContent: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], appNoticeContent: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], dingTalkNoticeContent: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], fsNoticeTitle: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], fsNoticeContent: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], dingTalkNoticeTitle: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ],
                  mpNoticeTitle: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ],
                  mpTemplateId: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ],
                  remindYourself: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ],
                  reminderTeam: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ],
                  isCustomSend: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ],
                  isCustomCc: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ]
                },
                listRules: {
                   fieldName: [{ required: true, message: this.$t('必填字段'), trigger: 'blur' }],
                   sourceField: [{ required: true, message: this.$t('必填字段'), trigger: 'blur' }],
                   toField: [{ required: true, message: this.$t('必填字段'), trigger: 'blur' }]
                 },
              sendUserEditor: {},
              ccUserEditor: {}
              }
        },
        created() {
            this.getDicts('sys_notice_type').then(response => {
                this.noticeModeOptions = response.data
            })
            this.getDicts('sys_yes_no').then(response => {
              this.sysYesNoOption = response.data
            })
        },
      methods: {
            // 初始化数据
            init(data) {
                this.loading = true
                if (data != null && data.id !== undefined) {
                    getMsgTemplate(data.id).then(response => {
                        this.form = response.data
                        this.$nextTick(() => {
                          if (response.data.isCustomSend === 'Y') {
                            this.onchange('send')
                            this.sendUserEditor.setValue(response.data.sendUserSql)
                          }
                          if (response.data.isCustomCc === 'Y') {
                            this.onchange('cc')
                            this.ccUserEditor.setValue(response.data.ccUserSql)
                          }
                        })
                        this.loading = false
                    })
                } else {
                    this.reset()
                    this.loading = false
                }
            },
        initEditor(ref) {
          const mime = 'text/x-mariadb'
          // let theme = 'ambiance'//设置主题，不设置的会使用默认主题
          return CodeMirror.fromTextArea(ref, {
            mode: mime, // 选择对应代码编辑器的语言，我这边选的是数据库，根据个人情况自行设置即可
            indentWithTabs: true,
            smartIndent: true,
            lineNumbers: true,
            matchBrackets: true,
            // theme: theme,
            // autofocus: true,
            extraKeys: { 'Ctrl': 'autocomplete' }, // 自定义快捷键
            hintOptions: { // 自定义提示选项
              tables: {
                users: ['name', 'score', 'birthDate'],
                countries: ['name', 'population', 'size']
              }
            }
          })
        },
        onchange(type) {
          if (type === 'send' && this.form.isCustomSend === 'Y') {
            this.sendUserEditor = this.initEditor(this.$refs.sendUserSql)
            this.sendUserEditor.on('cursorActivity', function() {
              if (this !== null) {
                this.sendUserEditor.showHint()
              }
            })
            this.sendUserEditor.setValue('')
          } else if (type === 'cc' && this.form.isCustomCc === 'Y') {
            this.ccUserEditor = this.initEditor(this.$refs.ccUserSql)
            this.ccUserEditor.on('cursorActivity', function() {
              if (this !== null) {
                this.ccUserEditor.showHint()
              }
            })
            this.ccUserEditor.setValue('')
          }
        },
          addMappingField() {
            var obj = {
              sourceField: undefined,
              toField: undefined,
              remark: undefined
            }
            if (!(this.form.mpMsgTemplateFieldMappingList instanceof Array)) {
              this.$set(this.form, 'mpMsgTemplateFieldMappingList', [])
            }
            this.form.mpMsgTemplateFieldMappingList.push(obj)
          },
            // 表单重置
            reset() {
                this.form = {
                id: undefined,
                noticeCode: undefined,
                noticeType: undefined,
                  sendUserSql: '',
                  ccUserSql: '',
                templateFieldList: [],
                  mpMsgTemplateFieldMappingList: [],
                  mpNoticeTitle: undefined,
                  mpTemplateId: undefined,
                remark: undefined,
                defaultSendUser: undefined,
                remindYourself: 'N',
                reminderTeam: 'Y',
                defaultSendRole: [],
                noticeMode: [],
                systemNoticeTitle: undefined,
                systemNoticeContent: undefined,
                dingTalkNoticeTitle: undefined,
                dingTalkNoticeContent: undefined,
                mailNoticeTitle: undefined,
                mailNoticeContent: undefined,
                appNoticeTitle: undefined,
                appNoticeContent: undefined,
                wechatNoticeTitle: undefined,
                wechatNoticeContent: undefined,
                smsNoticeCode: undefined,
                fsNoticeTitle: undefined,
                fsNoticeContent: undefined,
                createBy: undefined,
                createTime: undefined,
                updateBy: undefined,
                updateTime: undefined,
                delFlag: undefined,
                  isCustomSend: 'N',
                  isCustomCc: 'N'
                }
                this.resetForm('form')
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm() {
                // 关闭form页面遮罩层
                this.loading = false
                // 关闭form页面
                this.$parent.$parent.formOpen = false
                // 刷新list页面
                this.$parent.$parent.getList()
            },
            /** 提交按钮 */
            submitForm: function() {
                this.$refs['form'].validate(valid => {
                    if (valid) {
                      if (this.form.isCustomSend === 'Y') {
                        this.form.sendUserSql = this.sendUserEditor.getValue()
                      }
                      if (this.form.isCustomCc === 'Y') {
                        this.form.ccUserSql = this.ccUserEditor.getValue()
                      }
                      console.log(this.form)
                        this.loading = true
                        saveMsgTemplate(this.form).then(response => {
                            if (response.code === 200) {
                                this.msgSuccess(this.$t('保存成功'))
                                this.closeForm()
                            } else {
                                this.msgError(response.msg)
                            }
                            this.loading = false
                        }).catch(() => {
                          this.loading = false
                        })
                    } else {
                      this.locationError(document)
                    }
                })
           },
          addTemplate() {
            const row = {
              id: undefined,
              fieldName: undefined,
              remark: undefined
            }
            if (!(this.form.templateFieldList instanceof Array)) {
              this.$set(this.form, 'templateFieldList', [])
            }
            this.$nextTick(() => {
              this.form.templateFieldList.push(row)
            })
          },
          // 根据通知方式展示不同的组件
          noticeModeChange(val) {
              if (!val.includes('XTTX')) {
                this.form.systemNoticeTitle = undefined
                this.form.systemNoticeContent = undefined
              }
              if (!val.includes('EMAIL')) {
                this.form.mailNoticeTitle = undefined
                this.form.mailNoticeContent = undefined
              }
              if (!val.includes('APP')) {
                this.form.appNoticeTitle = undefined
                this.form.appNoticeContent = undefined
              }
              if (!val.includes('SMS')) {
                this.form.smsNoticeCode = undefined
              }
              if (!val.includes('QYWX')) {
                this.form.weChatNoticeTitle = undefined
                this.form.weChatNoticeContent = undefined
              }
          },
          // 删除关键字列表
          delTemplate(index) {
            this.form.templateFieldList.splice(index, 1)
          }
        }

    }
</script>

<style scoped lang="scss">
/deep/.mavon-editor li {
 list-style: unset !important;
}
/deep/.mappingData .el-form-item{
  min-height: unset;
}
/deep/.mappingData .el-form-item.is-error{
  min-height: 55px;
}
</style>
